package local.blueheart.data.springdatademo.controller;

import local.blueheart.data.springdatademo.annotation.TaskWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedType;
import java.util.HashMap;
import java.util.Map;

@Controller
@PreAuthorize("hasAnyAuthority('USER')")
public class IndexController extends BaseController {

    @Autowired
    private ApplicationContext applicationContext;

    @GetMapping("/index.do")
    public String index(){
        return "index";
    }

    @GetMapping("/taskList.do")
    public String taskList(){
        return "task";
    }

    @GetMapping("/allbean")
    @ResponseBody
    public Map<String,String> allCustomBean() {
        String[] beanNames = applicationContext.getBeanNamesForAnnotation(TaskWorker.class);
        Map<String,String> result = new HashMap<>();
        for(String beanName:beanNames){
            Object o = applicationContext.getBean(beanName);
            Annotation[] declaredAnnotations = o.getClass().getDeclaredAnnotations();
            for(Annotation annotation:declaredAnnotations){
                //TaskWorker workAnno = (TaskWorker) annotation;
                System.out.println(((TaskWorker) annotation).value()+","+o.getClass().getName());
                result.put(o.getClass().getName(),((TaskWorker) annotation).value());
            }
        }

        return result;
    }



}
